import os


def getProc(procName):
    pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
    for pid in pids:
        with open(os.path.join('/proc', pid, 'cmdline'), 'r') as f:
            process = f.read()
        if procName in process:
            return int(pid)
    return None


def killProc(pid):
    try:
        os.kill(pid, 2)
    except:
        print 'Could not kill process.'
    else:
        print 'Process killed.'


def main():
    procName = 'justpostprocessing.php'
    pid = getProc(procName)
    if not pid:
        print 'No process found for {}'.format(procName)
    else:
        killProc(pid)


class ProcessManager(object):

    def __init__(self, recallFileName):
        self.procNames = []
        self.file = recallFileName

    def getPID(self, name):
        pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
        for pid in pids:
            try:
                with open(os.path.join('/proc', pid, 'cmdline'), 'r') as f:
                    process = f.read()
                if name in process:
                    return int(pid)
            except Exception as e:
                continue
        return None

    def addProc(name):
        self.procNames.append(name)

    def checkProc(name, pid):
        if str(pid) in os.listdir('/proc'):
            try:
                with open(os.path.join('/proc', pid, 'cmdline'), 'r') as f:
                    process = f.read()
                if name in process:
                    return True
            except Exception as e:
                pass
        else:
            return self.getPID(name)

    def killSingleProc(self, name):
        pid = self.getPID(name)
        try:
            os.kill(pid, 2)
        except TypeError as e:
            return False, e
        except OSError as e:
            return False, e
        else:
            return True, None

    def killAllProc(self):
        for procName in self.procNames:
            self.killSingleProc(procName, self.pidDict[procName])

    def readFile(self):
        try:
            with open(self.recallFileName, 'r') as f:
                return f.readlines()
        except OSError:
            return None

    def writeFile(self, data):
        try:
            with open(self.recallFileName, 'a') as f:
                f.write(data)
        except OSError:
            return None

    def delFile(self):
        if os.path.exists(self.recallFileName):
            try:
                os.remove(self.recallFileName)
            except OSError:
                return None
